/*
# Rocket viewer is (c) BCNMedTech, UNIVERSITAT POMPEU FABRA
#
# Rocket viewer is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Rocket viewer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# Carlos Yagüe Méndez
# María del Pilar García
# Daniele Pezzatini
# Contributors: 
# Sergio Sánchez Martínez
*/

import { isObjectEmpty } from './../../../../../../../../modules/rkt_module_object';

// libraries
import NRRDLoader from './../../../../../../../../libraries/NRRDLoader';
import PLYLoader from './../../../../../../../../libraries/PLYLoader';
import VTKLoader from './../../../../../../../../libraries/VTKLoader';

//var dicomParser = require('dicom-parser');
var THREE = require('three');
var TrackballControls = require('three-trackballcontrols');

//Using global variables
const cornerstone = window.cornerstone;
const cornerstoneWADOImageLoader = window.cornerstoneWADOImageLoader;
const cornerstoneWebImageLoader = window.cornerstoneWebImageLoader;
const dicomParser = window.dicomParser;

export function isViewerLoadingAURLSource(img_url) {

    var viewerLoadingAURLResource = false;

    if (!isObjectEmpty(img_url)) {
        viewerLoadingAURLResource = true;
    }

    return viewerLoadingAURLResource;
}

export function getViewerType(files, url, callback) {

    var viewerType;

    if (isViewerLoadingAURLSource(url)) {
        // TO DO?
    } else {
        var fileType = files[0].type;


        if (!isObjectEmpty(fileType)) {

            switch (fileType) {
                case "application/dicom":
                    viewerType = "dicom";
                    break;

                case "image/tiff":
                    viewerType = "tiff";
                    break;

                case "application/pdf":
                    viewerType = "pdf";
                    break;

                default:
                    break;
            }

            callback(viewerType);

        } else {

            var nameFile = files[0].name;

            if (nameFile.includes(".nrrd")) callback("nrrd");
            else if (nameFile.includes(".ply")) callback("ply");
            else if (nameFile.includes(".vtk")) callback("vtk");
            else {
                isFileADicomFile(files[0], function (fileisDicom) {

                    if (fileisDicom) {
                        callback("dicom");
                    } else {
                        callback(undefined);
                    }

                })
            }
        }
    }
}

export function loadImage(viewerType, files, url, on_image_loaded_function, on_error_loading_function) {
    var img_url;

    switch (viewerType) {

        case "dicom":
            var img_source;

            if (isViewerLoadingAURLSource(url)) {
                img_url = url;
                img_source = "wado";
            }

            else {
                img_url = files;
                img_source = "filesystem";
            }

            loadDicom(img_url, img_source, on_image_loaded_function, on_error_loading_function);
            break;

        case "nrrd":
        case "ply":
        case "vtk":

            var dataURL = default_thumbnails_info[viewerType].localDataURL;

            createCornerstoneImage(dataURL, function (cornerstoneImage) {

                if (cornerstoneImage) {
                    on_image_loaded_function(cornerstoneImage);

                } else {
                    on_error_loading_function();
                }
            });

            break;

        default:
            break;
    }
}

export function getImageName(files, url) {

    var name;

    if (isViewerLoadingAURLSource(url)) {
        name = url.substring(url.lastIndexOf('/') + 1);

        if (url.includes("dl.dropboxusercontent") &&
            (name.includes("?dl=0"))) {
            name = name.replace("?dl=0", "");
        }

    } else {
        name = files[0].name;
    }

    return name;
}


////////////////////////// DICOM
function isFileADicomFile(file, callback) {
    try {
        loadFile(file, function (dicomFileAsBuffer) {
            try {
                var dataSet = dicomParser.parseDicom(dicomFileAsBuffer);
                callback(true);
            }
            catch (exceptionParseDicom) {
                callback(false);
            }
        });

    } catch (exceptionFileReader) {
        callback(false);
    }

    // based on view-source:https://rawgit.com/chafey/dicomParser/master/examples/gettingStarted/index.html
    function loadFile(file, callback) {
        var reader = new FileReader();

        reader.onload = function (file) {
            var arrayBuffer = reader.result;
            var byteArray = new Uint8Array(arrayBuffer);
            callback(byteArray);
        }

        reader.readAsArrayBuffer(file);
    }
}

export function loadDicom(url, img_source, on_image_loaded_function, on_error_loading_function) {

    if (img_source === "filesystem") {
        loadLocalImage(url, on_image_loaded_function, on_error_loading_function);
    }
    else if (img_source === "wado") {
        loadWADOImage(url, on_image_loaded_function, on_error_loading_function);
    }
}

function loadLocalImage(url, on_image_loaded_function, on_error_loading_function) {

    var imageId = cornerstoneWADOImageLoader.fileManager.add(url[0]);
    cornerstone.loadImage(imageId).then(
        on_image_loaded_function,
        function (err) {
            on_error_loading_function();
        });
}

function loadWADOImage(url, on_image_loaded_function, on_error_loading_function) {

    var imageId = "wadouri:" + url + "?frame=0";

    try {
        cornerstone.loadAndCacheImage(imageId).then(
            on_image_loaded_function,
            function (err) {
                on_error_loading_function();

            });
    }
    catch (err) {
        alert(err);
    }
}

function createCornerstoneImage(dataURL, callback) {
    var imageId = "3d-model";
    var image = new Image();
    image.src = dataURL;

    image.onload = function () {

        var imageObject = cornerstoneWebImageLoader.createImage(image, imageId);
        callback(imageObject);

    };
    image.onerror = function (err) {

        alert("Problems loading the image");
        callback(false);
    };
}


export function getDicomMetadata(cornerstoneImage) {
    var dicomData = {};
    var allMetadata = cornerstoneImage.data;
    
    var imageData = cornerstoneImage.data;
    var dicomFileAsBuffer = imageData.byteArray;
    var dicomDataset = dicomParser.parseDicom(dicomFileAsBuffer);
    var options = {
        omitPrivateAttibutes: true,
        maxElementLength: 128
    };
    var dataSetJSON = dicomParser.explicitDataSetToJS(dicomDataset, options);


    dicomData["patient_name"] = dataSetJSON['x00100010'];
    dicomData["modality"] = dataSetJSON['x00080060'];
    dicomData["manufacturer"] = dataSetJSON['x00080070'];//dataSetJSON['x00081090']; <-- this is tag "Model"
    dicomData["acquisition_time"] = dataSetJSON['x0008002a'];

    if (!isObjectEmpty(dataSetJSON['x00186011'])) {

        var dicomRegions = dataSetJSON['x00186011'];
        var arrayOfRegions = [];

        for (var i = 0; i < dicomRegions.length; i++) {

            var dicomRegion = {};
            dicomRegion["region_spatial_format"] = dicomRegions[i]['x00186012'];
            dicomRegion["region_data_type"] = dicomRegions[i]['x00186014'];
            dicomRegion["region_flags"] = dicomRegions[i]['x00186016'];
            dicomRegion["region_location_min_x0"] = dicomRegions[i]['x00186018'];
            dicomRegion["region_location_min_y0"] = dicomRegions[i]['x0018601a'];
            dicomRegion["region_location_max_x1"] = dicomRegions[i]['x0018601c'];
            dicomRegion["region_location_max_y1"] = dicomRegions[i]['x0018601e'];
            dicomRegion["reference_pixel_x0"] = dicomRegions[i]['x00186020'];
            dicomRegion["reference_pixel_y0"] = dicomRegions[i]['x00186022'];
            dicomRegion["physical_units_x_direction"] = dicomRegions[i]['x00186024'];
            dicomRegion["physical_units_y_direction"] = dicomRegions[i]['x00186026'];
            dicomRegion["physical_delta_x"] = dicomRegions[i]['x0018602c'];
            dicomRegion["physical_delta_y"] = dicomRegions[i]['x0018602e'];
            dicomRegion["transducer_frequency"] = dicomRegions[i]['x00186030'];
            arrayOfRegions.push(dicomRegion);
        }

        dicomData["Sequence_of_ultrasound_regions"] = arrayOfRegions;

    }

    if (!isObjectEmpty(dataSetJSON["x00181088"])) {
        dicomData["heart_rate"] = dataSetJSON["x00181088"];
    }

    return dicomData;

}

var default_thumbnails_info = [];
default_thumbnails_info["nrrd"] = {
    "serverDataURL": "https://www.dl.dropboxusercontent.com/s/8rdmwwzjk4tlbjw/thumbnail_nrrd.jpg?dl=0",
    "localDataURL": ""
}
default_thumbnails_info["ply"] = {
    "serverDataURL": "https://www.dl.dropboxusercontent.com/s/0raq9zb4xvs7tsg/thumbnail_ply.jpg?dl=0",
    "localDataURL": ""
}
default_thumbnails_info["vtk"] = {
    "serverDataURL": "https://www.dl.dropboxusercontent.com/s/8rdmwwzjk4tlbjw/thumbnail_nrrd.jpg?dl=0",
    "localDataURL": ""
}